package wqh.websocket.device_websocket;


import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.socket.*;

import java.io.IOException;
import java.util.ArrayList;

public class DeviceSocketHandler implements WebSocketHandler{

    private static final Logger logger;
    private static final ArrayList<WebSocketSession> sessionList;

    static{
        sessionList = new ArrayList<WebSocketSession>();
        logger = LoggerFactory.getLogger(DeviceSocketHandler.class);
    }

    public void afterConnectionEstablished(WebSocketSession webSocketSession) throws Exception {
        if(webSocketSession != null)
        {
            System.out.println("成功建立socket连接");
            sessionList.add(webSocketSession);
        }
    }

    public void handleMessage(WebSocketSession webSocketSession, WebSocketMessage<?> webSocketMessage) throws Exception {

    }

    public void handleTransportError(WebSocketSession webSocketSession, Throwable throwable) throws Exception {
        if(webSocketSession.isOpen())
        {
            webSocketSession.close();
        }
//        logger.error("连接出现错误:"+throwable.toString());
        sessionList.remove(webSocketSession);

    }

    public void afterConnectionClosed(WebSocketSession webSocketSession, CloseStatus closeStatus) throws Exception {
        System.out.println("连接已关闭");
        sessionList.remove(webSocketSession);
    }

    public boolean supportsPartialMessages() {
        return false;
    }

    public void sendMessageToSessionList(TextMessage message) {
        for (WebSocketSession session : sessionList) {
            try {
                if (session.isOpen()) {
                    session.sendMessage(message);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

}
